# coding = utf-8
import datetime

from django.db.models import Count
from rest_framework import serializers

from member.models import RetailerImage, Retailer, Employee, BonusPoint, PointConsumption, WxRole, WxPermission

from rest_framework.serializers import ModelSerializer


class RetailerImageSerializer(ModelSerializer):
    """
    商家图片
    """
    class Meta:
        model = RetailerImage
        exclude = ["update_time", "add_time"]


class RetailerSerializer(ModelSerializer):
    """
    商家管理
    """
    flag_name = serializers.CharField(source='get_flag_display', read_only=True)


    class Meta:
        model = Retailer
        exclude = ["update_time", "add_time"]


class RetailerListSerializer(ModelSerializer):
    """
    商家管理
    """
    records = serializers.SerializerMethodField()

    class Meta:
        model = Retailer
        fields = ["id", "name", "address", "records"]

    def get_records(self, obj):
        counts = obj.records.filter(balance_flag=0).count()
        return counts


class EmployeeSerializer(ModelSerializer):
    """
    商家授权员工
    """
    role_name = serializers.CharField(source='role.name', read_only=True)

    class Meta:
        model = Employee
        exclude = ["update_time", "add_time"]


class BonusPointSerializer(ModelSerializer):
    """
    商家积分赠送明细
    """
    retailer_name = serializers.CharField(source='retailer.name', read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    cancel_flag = serializers.SerializerMethodField(read_only=True)
    status_name = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = BonusPoint
        exclude = ["add_time"]

    def get_cancel_flag(self, obj):
        curr_datetime = datetime.datetime.now()
        diff_hour = (curr_datetime - obj.update_time).total_seconds() / 3600
        return diff_hour <= 24


class PointConsumptionSerializer(ModelSerializer):
    """
    客户积分消费
    """
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = PointConsumption
        exclude = ["add_time"]


class WxPermissionSerializer(ModelSerializer):
    """
    权限信息
    """
    flag_name = serializers.CharField(source='get_flag_display', read_only=True)

    class Meta:
        model = WxPermission
        exclude = ["update_at", "create_at"]


class WxRoleSerializer(ModelSerializer):
    """
    角色信息
    """
    retailer_name = serializers.CharField(source='retailer.name', read_only=True)
    perms = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = WxRole
        exclude = ["update_at", "create_at"]

    def get_perms(self, obj):
        queryset = obj.permissions.all()
        perm_list = []
        for item in queryset:
            perm_list.append(item.name)
        return ','.join(perm_list)
